'use strict';

const Service = require('egg').Service;

class TableService extends Service {
  async createTable(code,description,areaId,persons) {
    try{
        const insertResult =await this.app.mysql.insert('tablez',{
            code:code,
            description:description,
            persons:persons
        });
        const relationResult =await this.app.mysql.insert('area_table',{aid:areaId,tid:insertResult.insertId});
        if (insertResult.affectedRows === 1 && relationResult.affectedRows === 1){
            return 'success';
        }else{
            return 'failed';
        }
    }catch(error){
        return error.message;
    }

  }

  async tableList(){
      const rid = this.ctx.request.headers['rid'];
      var arealist =await this.ctx.service.table.areaservice.getAreaList();
      try{
          for (var i=0;i!= arealist.length;++i){
            arealist[i].tableList = await this.app.mysql.query('SELECT tablez.* FROM area_table INNER JOIN tablez ON area_table.tid = tablez.id WHERE area_table.aid = ?',[arealist[i].id]);      
          }
          return arealist;
      }catch(err){
          return err;
      }

  }


  async deleteTable(tid){
      try{
        const result = await this.app.mysql.delete('tablez',{id:tid});
        const relation = await this.app.mysql.delete('area_table',{tid:tid});
        if (result.affectedRows === 1 && relation.affectedRows === 1){
            return true;
        }else{
            return false;
        }
      }catch(err){
        return false;
      }
      
  }
}

module.exports = TableService;
